import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class RecordListWidget extends StatelessWidget {
  final List<Map<String, dynamic>> recordSegments;
  final bool isLoading;
  final bool hasMore;
  final Function(Map<String, dynamic>) onRecordTap;
  final Function(Map<String, dynamic>)? onDownloadTap;

  const RecordListWidget({
    super.key,
    required this.recordSegments,
    required this.isLoading,
    required this.hasMore,
    required this.onRecordTap,
    this.onDownloadTap,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 录像片段列表
        Expanded(child: _buildRecordList()),
      ],
    );
  }

  /// 构建录像片段列表
  Widget _buildRecordList() {
    if (recordSegments.isEmpty) {
      // 检查是否正在加载
      if (isLoading) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(color: Color(0xFF047FF7)),
              SizedBox(height: 20.h),
              Text(
                '正在加载录像数据...',
                style: TextStyle(fontSize: 28.sp, color: Color(0xFF999999)),
              ),
            ],
          ),
        );
      }

      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 空状态图片
            Image.asset('assets/images/null.png', width: 378.w, height: 378.w),
            SizedBox(height: 40.w),
            Text(
              '暂无录像数据',
              style: TextStyle(fontSize: 28.sp, color: const Color(0xFF999999)),
            ),
          ],
        ),
      );
    }

    // 按小时分组显示真实数据
    final groupedSegments = _groupSegmentsByHour(recordSegments);

    return ListView.builder(
      padding: EdgeInsets.all(16.w),
      itemCount: groupedSegments.keys.length,
      itemBuilder: (context, index) {
        final hour = groupedSegments.keys.elementAt(index);
        final hourSegments = groupedSegments[hour]!;
        return _buildHourGroup(hour, hourSegments);
      },
    );
  }

  /// 按小时分组录像片段
  Map<int, List<Map<String, dynamic>>> _groupSegmentsByHour(
    List<Map<String, dynamic>> segments,
  ) {
    final Map<int, List<Map<String, dynamic>>> grouped = {};

    for (final segment in segments) {
      final hour = segment['hour'] as int? ?? 0;
      if (grouped[hour] == null) {
        grouped[hour] = [];
      }
      grouped[hour]!.add(segment);
    }

    return grouped;
  }

  /// 构建小时分组
  Widget _buildHourGroup(int hour, List<Map<String, dynamic>> hourSegments) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 小时标题
        Padding(
          padding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 16.w),
          child: Text(
            '${hour.toString().padLeft(2, '0')}:00',
            style: TextStyle(
              fontSize: 28.sp,
              fontWeight: FontWeight.w600,
              color: Color(0xFF333333),
            ),
          ),
        ),

        // 该小时的录像片段列表
        ...hourSegments.map((segment) => _buildRecordItem(segment)),
      ],
    );
  }

  /// 构建录像片段项
  Widget _buildRecordItem(Map<String, dynamic> segment) {
    final time = segment['time'] as String? ?? '';
    final duration = segment['duration'] as String? ?? '';
    final type = segment['type'] as String? ?? 'motion';
    final fileName = segment['fileName'] as String? ?? '';

    return GestureDetector(
      onTap: () => onRecordTap(segment),
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(color: Color(0xFFE5E7EB), width: 1.w),
        ),
        child: Row(
          children: [
            // 录像类型图标
            Container(
              width: 48.w,
              height: 48.w,
              decoration: BoxDecoration(
                color: Color(0xFF047FF7).withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Icon(
                Icons.videocam,
                size: 24.sp,
                color: Color(0xFF047FF7),
              ),
            ),

            SizedBox(width: 16.w),

            // 录像信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    fileName,
                    style: TextStyle(
                      fontSize: 28.sp,
                      fontWeight: FontWeight.w500,
                      color: Color(0xFF333333),
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 8.h),
                  Row(
                    children: [
                      Text(
                        time,
                        style: TextStyle(
                          fontSize: 24.sp,
                          color: Color(0xFF666666),
                        ),
                      ),
                      SizedBox(width: 16.w),
                      Text(
                        duration,
                        style: TextStyle(
                          fontSize: 24.sp,
                          color: Color(0xFF666666),
                        ),
                      ),
                      SizedBox(width: 16.w),
                      Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 8.w,
                          vertical: 4.h,
                        ),
                        decoration: BoxDecoration(
                          color: _getTypeColor(type).withValues(alpha: 0.1),
                          borderRadius: BorderRadius.circular(4.r),
                        ),
                        child: Text(
                          _getTypeText(type),
                          style: TextStyle(
                            fontSize: 20.sp,
                            color: _getTypeColor(type),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),

            // 下载图标
            GestureDetector(
              onTap: () {
                if (onDownloadTap != null) {
                  onDownloadTap!(segment);
                }
              },
              child: Icon(Icons.download, size: 24.sp, color: Color(0xFF047FF7)),
            ),
          ],
        ),
      ),
    );
  }

  /// 获取录像类型颜色
  Color _getTypeColor(String type) {
    switch (type) {
      case 'motion':
        return Color(0xFF047FF7);
      case 'alarm':
        return Color(0xFFFF6B6B);
      case 'manual':
        return Color(0xFF4CAF50);
      default:
        return Color(0xFF999999);
    }
  }

  /// 获取录像类型文本
  String _getTypeText(String type) {
    switch (type) {
      case 'motion':
        return '移动侦测';
      case 'alarm':
        return '报警录像';
      case 'manual':
        return '手动录像';
      default:
        return '录像';
    }
  }
}
